const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
  async getAction() {
    let data;
    if (this.id) {
      const pk = this.modelInstance.pk;
      data = await this.modelInstance.where({[pk]: this.id}).find();
      data.create_time = this.utils.datetime(data.create_time, 'YYYY-MM-DD HH:mm');
      this.utils.splitAttributes(data, ['image_ids', 'tags']);
      data.images = [];
      for (const image_id of data.image_ids) {
        const url = await this.utils.getImageFullPath(image_id);
        if (!think.isEmpty(url)) {
          data.images.push(url);
        }
      }
      
      return this.success(data);
    }
    
    const map = {};
    const type = this.get('type'); // 丢失还是捡到
    if (type) {
      map['type'] = type; // 支持lost,found两种类型
    }
    
    const key = this.get('key');
    if (key) {
      map['title|address|mobile|linkman|description'] = ['LIKE', '%' + key + '%']; // 支持关键字查找，模糊匹配
    }
    
    const page = this.get('page');
    if (page) {
      const pageSize = this.get('pageSize') || 10;
      data = await this.modelInstance.page(page, pageSize).order('create_time desc').where(map).countSelect();
    } else {
      data = await this.modelInstance.where(map).order('create_time desc').select();
    }
    
    for (let item of data.data) {
      item.create_time = this.utils.datetime(item.create_time, 'YYYY-MM-DD HH:mm');
      
      this.utils.splitAttributes(item, ['image_ids', 'tags']);
      let images = [];
      for (const image_id of item.image_ids) {
        let url = await this.utils.getImageFullPath(image_id);
        if (!think.isEmpty(url)) {
          images.push(url);
        }
      }
      item.images = images;
    }
    return this.success(data);
  }
  
  async postAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    delete data[pk];
    
    if (think.isEmpty(data)) {
      return this.fail('data is empty');
    }
    
    data.create_time = this.utils.getTime(); //创建时间
    
    const insertId = await this.modelInstance.add(data);
    if (insertId) {
      data[pk] = insertId;
      // await this.hook(this.resource + 'Create', data);
    }
    return this.success({id: insertId});
    
  }
};
